$(function()
{
    
    if($('#calendar_navigation').length) {
        
        $('#calendar_navigation').datepicker({
            dateFormat: 'dd-mm-yy', 
            defaultDate: $.datepicker.parseDate('d-m-y', date), 
            onSelect: function(dateText, inst) 
            { 
                document.location.href = '/?date=' + dateText + '&food_intake_code=1'; 
            }
        });
        
    }
    
    /**
    * Products autocomplete
    * 
    */
    function tag_add() 
    {
        $('.tag_add_input').tag_add({
            maxitem:0, // max item for out, 0-show all
            minlength:1, // min length str for search tags
            maxlength:10, // max length str for search tags
            loadinfo: 'products/autocomplete-list.html' //file - data tags
        });
    }
    tag_add();
    
    var default_message_error = 'Хочешь убрать все продукты?';
    
    /**
    * Add row
    * 
    */
    function add_row(clicked_object) 
    {
        var cloned = $(clicked_object).parents('tr').clone();
        // clear values
        cloned.find('input[type=text]').val('');
        // remove errors
        cloned.find('ul').remove();
        
        $(clicked_object).parents('tr').after(cloned).next().find('td:first input').focus();
        
        tag_add();
        fix_numeration();
    }
    $('input.gramme_input').live('keydown', function(event)
    {
        // Tab
        if (9 == event.which) {
            add_row(this);
            event.preventDefault();
        }
        
    });
    $('span.add').live('click', function()
    {
        add_row(this);
    });
    
    /**
    * Remove row
    * 
    */
    $('span.remove').live('click', function()
    {
        var row = $(this).parents('tr');
        
        if ($('#products tr').length > 2) {
            row.remove(); 
            fix_numeration();
        } else {
            alert(default_message_error);
        }
    });
    
    /**
    * Fix table numeration
    * 
    */
    function fix_numeration() 
    {
        $('#products tr').each(function(i)
        {
            // rows except header row
            if (i > 0) {
                $(this).find('td').each(function(j)
                {
                    switch(j) 
                    {
                        // cells with product name and gramme number
                        case 0 : 
                        case 1 : 
                            // re-numerate names
                            var name_pattern = /^([a-z_]+)\d+$/;
                            $(this).find('input').attr('name', 
                                $(this).find('input').attr('name')
                                    .replace(name_pattern, '$1' + i));
                            break;
                    }
                });
            }
        });
    }
    
    /**
    * Products DB grid
    * 
    */
    $('#content tr:not(:first)')
    .hover(function()
    {
        $(this).addClass('hover');
    }, function()
    {
        $(this).removeClass('hover');
    });
    
    // edit
    $('#content tr:not(:first) td:not(:first-child)', '#container')
    .css('cursor', 'pointer')
    .click(function()
    {
        var query_string = $.param({
            id: $(this).parent('tr').attr('id'), 
            letter: $.query.get('letter'), 
            page: $.query.get('page')
        });
        document.location.href = '/products/edit.html?' + query_string; 
    });
    
    // delete
    $('#products_delete').submit(function()
    {
        if ($('#content tr:not(:first) td:first-child input:checked').length) {
            return confirm('Точно?');
        } else {
            alert('Нечего же удалять!');
            return false;
        }
    });
    
    /**
    * Background product validation
    * 
    */
    var image = new Image();
    $(image).load(function(){$(this.hide);}).attr('src', 'images/spinner.gif');
    
    $('input#name').blur(function()
    {
        var name = $(this).val();
        if ($.trim(name)) {
            $('input#name').after(image);
            
            $.get('products/is-exist.html', 
                {
                    name: name, 
                    exclude: $('#id').val(), 
                    format: 'json'
                }, 
                function(response)
                {
                    $('input#name').parent()
                        .find('ul').remove().end()
                        .find('img').remove();
                    if (response.status) 
                    {
                        
                        $('input#name')
                            .after('<ul class="errors"><li>\
                            ' + response.message + '</li></ul>');
                        
                        var components = response.product.content;
                        $('form#new_product input[class=components]').each(function()
                        {
                            var code = $(this).attr('name').substr(10);
                            for (i=0; i<components.length; i++) {
                                if (components[i].component_code == code) {
                                    $(this).val(components[i].value);
                                }
                            }
                        });
                            
                    }
                }
            , 'json');
        }
    });
    
});
